//
//  MTMsgViewController.m
//  YuchBox
//
//  Created by Ivan on 11-9-29.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "MTMsgViewController.h"
#import "MTRootToolBarViewController.h"
#import "YuchBoxAppDelegate.h"

#import "Utility.h"

@implementation MTMsgViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#define LABEL_TAG   100
- (void)loadCurrentLog
{
    NSString *logDictPath = [TTLog getLogDictionaryPath];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMMdd"];
    
    NSString *logFilePath = [NSString stringWithFormat:@"%@/%@.log", logDictPath, [dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSinceNow:0]]];
    [dateFormatter release];
//    NSError *error;
    NSDictionary *fileAttr = [[NSFileManager defaultManager] attributesOfItemAtPath:logFilePath error:nil];
    
    NSInteger fileSize = [[fileAttr objectForKey:NSFileSize] intValue];    

    NSLog(@"fileSize: %d", fileSize);
    NSInputStream *fileInputStream = [NSInputStream inputStreamWithFileAtPath:logFilePath];
    [fileInputStream open];

    if ([fileInputStream hasBytesAvailable]) {
        
#define LOG_BUFFER_SIZE 100*1024
        UILabel *label = (UILabel *)[_logScrollView viewWithTag:LABEL_TAG];
        UInt8 *buffer = (UInt8 *)malloc(LOG_BUFFER_SIZE);
        
        NSInteger unReadSize = fileSize;
        while (unReadSize > 0) {
            NSInteger readBufferSize = MIN(unReadSize, LOG_BUFFER_SIZE);
            NSInteger readSize = [fileInputStream read:buffer maxLength:readBufferSize];
            NSString *text = [NSString stringWithUTF8String:(const char *)buffer];
            label.text = [NSString stringWithFormat:@"%@", text];
            
            unReadSize -= readSize;
        }
        
        CGSize size = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(700, 300000) lineBreakMode:UILineBreakModeClip];
        label.frame = CGRectMake(0, 0, 700, size.height);
        _logScrollView.contentSize = CGSizeMake(700, size.height + 400);
        [_logScrollView setContentOffset:CGPointMake(0, size.height < 100 ? 0 : size.height - 100)];
    }
    
    [fileInputStream close];
    
}

- (void)setBarItems
{
    MTRootToolBarViewController *rootViewController =  [YuchBoxAppDelegate shareAppDelegate].rootToolBarViewController;
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
    //    titleView.backgroundColor = [UIColor blueColor];
    
    UIButton *refreshButton = [UIButton buttonWithType:UIButtonTypeCustom];
    refreshButton.frame = CGRectMake(10, 7, 26, 26);
    [refreshButton addTarget:self action:@selector(loadCurrentLog) forControlEvents:UIControlEventTouchUpInside];
    [refreshButton setBackgroundImage:[UIImage imageNamed:@"bar_refresh"] forState:UIControlStateNormal];
    [titleView addSubview:refreshButton];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(140, 0, 80, 40)];
    label.backgroundColor = [UIColor clearColor];
    
    label.text = @"诊断日志";
    label.font = [UIFont boldSystemFontOfSize:16];
    label.textColor = [UIColor whiteColor];
    [titleView addSubview:label];
    [label release];
    
    [rootViewController.navigationItem setTitleView:titleView];
    [titleView release];
}

- (void)clearBarItems
{
    MTRootToolBarViewController *rootViewController =  [YuchBoxAppDelegate shareAppDelegate].rootToolBarViewController;
    
//    [rootViewController.navigationController.view setHidden:YES];
    [rootViewController.navigationItem setLeftBarButtonItem:nil];
    [rootViewController.navigationItem setTitle:@""];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _logScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
    
//    [_logScrollView setCanCancelContentTouches:NO];
    [_logScrollView setDirectionalLockEnabled:YES];
//    [_logScrollView setShowsHorizontalScrollIndicator:YES];
    [_logScrollView setClipsToBounds:YES];
    [_logScrollView setMinimumZoomScale:0.5f];
    [_logScrollView setMaximumZoomScale:2.0f];
    [_logScrollView setZoomScale:1.0f];
    _logScrollView.delegate = self;
//     Field *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, 0, 0)];
    
//    _logScrollView.contentSize = CGSizeMake(320, 600);
    label.numberOfLines = 0;
    
    label.font = [UIFont fontWithName:@"CourierNewPSMT" size:9];
    label.tag  = LABEL_TAG;
    [_logScrollView addSubview:label];
    [label release];

    [self.view addSubview:_logScrollView];
//    [self loadCurrentLog];
    [self loadCurrentLog];

}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    [_logScrollView release];
}

- (void)viewWillAppear:(BOOL)animated
{
//    [self setBarItems];
}

- (void)viewDidDisappear:(BOOL)animated
{
//    [self clearBarItems];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - 
#pragma IvanTabBarDelegate
- (void)viewWillAppearIvan:(BOOL)animated
{
//    NSLog(@"^^^^ will appearIvan");
    [self setBarItems];
}

- (void)viewWillDisappearIvan:(BOOL)animated
{
//    NSLog(@"^^^^ did disappearIvan");
    [self clearBarItems];
}

- (NSInteger)showViewSequence
{
    return 0x3423;
}
@end
